/**
//给定一棵二叉树，设计一个算法，创建含有某一深度上所有节点的链表（比如，若一棵树的深度为 D，则会创建出 D 个链表）。返回一个包含所有深度的链表的数组。 
//
// 
//
// 示例： 
//
// 输入：[1,2,3,4,5,null,7,8]
//
//        1
//       /  \ 
//      2    3
//     / \    \ 
//    4   5    7
//   /
//  8
//
//输出：[[1],[2,3],[4,5,7],[8]]
// 
// Related Topics 树 广度优先搜索 链表 二叉树 👍 61 👎 0

*/

package com.xixi.dataStructure.tree.binaryTree;

import com.xixi.dataStructure.lineList.ListNode;
import com.xixi.dataStructure.tree.TreeNode;

import java.util.ArrayList;
import java.util.List;

public class ID_InterView_04_03_ListOfDepthLcci {
public static void main(String[] args) {
Solution solution = new ID_InterView_04_03_ListOfDepthLcci().new Solution();
}


//leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {

    List<TreeNode> thisLevel = new ArrayList<>();
    List<TreeNode> nextLevel;
/*
 * @Desc: 按曾遍历树
 * @Author vincentML
 * @Date: 2021/11/29 17:06
 * @param tree
 * @return com.xixi.dataStructure.lineList.ListNode[]
*/

    public ListNode[] listOfDepth(TreeNode tree) {
        if(tree == null) return null;

        List<ListNode> res = new ArrayList<>();
        thisLevel.add(tree);


        while(!thisLevel.isEmpty()){ //当前层不空
            nextLevel = new ArrayList<>();
            ListNode thisLevelListHead = null;
            ListNode thisLevelListTail = new ListNode();
            //循环一层
            for(int i = 0; i < thisLevel.size(); ++i){
                TreeNode nowNode = thisLevel.get(i);
                ListNode newNode = new ListNode(nowNode.val);
                if(thisLevelListHead == null){ //链表头才赋值, 新起一行
                    thisLevelListHead = newNode;
                    res.add(thisLevelListHead);
                }

                thisLevelListTail.next = newNode; //尾插赋值
                thisLevelListTail = newNode; //尾部指针指向新节点

                //先左后右添加
                if(nowNode.left !=null ){
                    nextLevel.add(nowNode.left);
                }
                if(nowNode.right !=null ){
                    nextLevel.add(nowNode.right);
                }

            }
            thisLevel.clear();
            thisLevel = nextLevel; //指针指向下一层

        }
        ListNode[] result = new ListNode[res.size()]; //结果转换
        return res.toArray(result);

    }
}
//leetcode submit region end(Prohibit modification and deletion)




}